<!--
 * Date: 2018年01月11日 10:24:49
 * LastEditors  : lvyou
 * LastEditTime : 2020年01月03日 14:18:56
 * FilePath: \youlinweb-master\src\pages\mine\chatlog.vue
 * copyright(c) 2019-2025 版权为浙江双城网络科技集团有限公司所有，违者必究。
 -->
<!--
 * Date: 2018年01月11日 10:24:49
 * LastEditors: lvyou
 * LastEditTime: 2020年01月02日 19:06:14
 * FilePath: \youlinweb-master\src\pages\mine\chatlog.vue
 * copyright(c) 2019-2025 版权为浙江双城网络科技集团有限公司所有，违者必究。
 -->
<template>
  <div style="height:100%;position:relative;" class="touch_action">
    <ylheader :leftsvg="true" :title="'留言'"></ylheader>
    <pull-to-refresh v-if="chatLogDetailList.length" @on-pullup='onPullup' @on-pulldown='onPulldown' class="chatlist">
      <ul>
        <template v-for="(item,index) in chatLogDetailList">
          <li class="chat-mine" v-if="item.chatType==1" :key="index">
            <div class="chat-user" v-if="item.isshow">
               <div class="pendant-container">
                <img :src="headUrl" class="chat-head">
                <img :src="item.pendantPicUrl"  class="pendant" v-if="item.pendantType!=0&&item.pendantPicUrl">
                <img src="https://youlingqinius.wonderlandnet.cn/youlin-shengdan@2x.png"  class="pendant" v-else-if="item.pendantType==1">
                <img src="https://youlingqinius.wonderlandnet.cn/youlin-yuandan@2x.png"  class="pendant" v-else-if="item.pendantType==2">
                <img src="https://youlingqinius.wonderlandnet.cn/youlin-chunjie@2x.png"  class="pendant" v-else-if="item.pendantType==3">
                <img src="https://youlingqinius.wonderlandnet.cn/youlin-yuanxiao@2x.png"  class="pendant" v-else-if="item.pendantType==4">
                <img src="~img/daren.png" v-else-if="item.isTalent==1"  class="vipimg v-h" style="width:0.24rem;height:0.24rem">
               </div>
            </div>
            <div class="time" v-if="item.isshow">
              <cite>
                <i>{{item.createTimeStamp}}</i>{{nickName}}</cite>
            </div>
            <div class="chat-text" v-if="item.contentType==1" style="background-color: #fd996d;" v-html="item.content">{{item.content}}</div>
            <div class="chat-img-text" v-if="item.contentType==2"><img v-lazy="item.content+'/thumbnail/!339x239r/gravity/Center/crop/339x239'" class="previewer-demo-img preview-img-item onecommentimg "  style="width:3.39rem;height:2.39rem;border-radius:8px 0px 8px 8px;;margin-left:10px"  @click="saveimgtolocal(item.content)"></div>
          </li>
          <li v-if="item.chatType==2" :key="index">
            <div class="withdraw h-c" v-if="item.recallType==1">对方撤回了一条消息</div>
            <div v-else>
              <div class="chat-user" v-if="item.isshow">
                <img src="https://youlingqinius.wonderlandnet.cn/littlegreen.png" style="width:0.8rem;height:0.8rem">
                 <img src="~img/vip.png" v-if="item.isshow" class="v-h" style="width:0.24rem;height:0.24rem;position:absolute;right:0;bottom:0">
              </div>
              <div class="time" v-if="item.isshow">
                <cite>{{item.name}}
                  <i>{{item.createTimeStamp}}</i>
                </cite>
              </div>
              <div class="chat-littegreen-text" v-if="item.contentType==1"  v-html="item.content">{{item.content}}</div>
              <div class="chat-img-text" v-if="item.contentType==2"><img v-lazy="item.content+'?imageMogr2/auto-orient/thumbnail/!339x239r/gravity/Center/crop/339x239'" class="previewer-demo-img preview-img-item onecommentimg "  style="padding:0;width:3.39rem;height:2.39rem;border-radius: 0 8px 8px 8px;"  @click="saveimgtolocal(item.content)"></div>
            </div>
          </li>
        </template>
      </ul>
      <p style="padding-bottom:55px;"></p>
    </pull-to-refresh>

    <section class="foot">
      <input id="txtContent" type="text" placeholder="输入您想说的..." class="con" v-model="content"/>
       <div class="body-sep"></div>
      <span class="btn yl-2ly-jia" style="position:absolute;right:1.25rem;height:1rem;line-height:1rem;color:#949494;font-size: 0.48rem;"></span>
      <input multiple="multiple" type="file" class="myinput" accept="image/gif, image/jpeg, image/png,image/jpg" @change="createImage($event)" />
      <div class="btn-send" @click="sendMsg">发送</div>
    </section>
  </div>
</template>
<script>
import ylheader from "src/components/yl-header.vue";
import PullToRefresh from 'src/components/pull-to-refresh'
import api from "src/api/index";
import { mapState, mapMutations } from "vuex";
import axios from "axios";
export default {
  name:"chatlog",
  data() {
    return {
      chatPage: {
        page: 1,
        limit: 10,
      },
      totalPage: 0,
      adminstarttimestamp: "",//计算小绿5分钟开始时间戳
      userstarttimestamp: "",//计算用户5分钟开始时间戳
      sendnewmsgtimestamp: "",//用户发送新的对话时间戳
      nickName: localStorage.getItem("nickName"),
      headUrl: localStorage.getItem("headImg"),
      tempdate: "",
      thumbnailslist: [],
      list: [],
      token: "",
      topStatus: "",
      content: "",
      chatLogDetailList: [],
      autoreply: {
        adminId: 1,
        chatLogId: 100,
        chatType: 2,//1-用户，2-小绿
        content: "终于等到你了，小绿已经等了好久啦！在这不仅和小伙伴们进行互动还可以领取超多福利，赶快去首页参与吧~",
        contentType: 1,
        createTimeStamp: "",
        headUrl: null,
        id: 102,
        lastChangeTimeStamp: "",
        name: "小绿",
        userId: 1,
        imgstr:[],//点击放大
      }
    };
  },
  computed: {
    ...mapState(["notreadmsg"])
  },
  mounted() {
    //判断用户第一次进入
    if (localStorage.getItem("isfirstin") == true) {
      localStorage.setItem("isfirstin", JSON.stringify(false))
    }
    this.updatanotreadnum();
    this.getChatLogDetailList().then(data => {
      this.$nextTick(() => {
        setTimeout(() => {
          this.$bus.$emit('scrollToBottom');
        }, 60)
      });
    })
    this.getqiuniutoken();
  },
  methods: {
     ...mapMutations(["changenotreadmsg"]),
    //解决ios输入框被输入法弹出后遮挡问题
    onPullup(finshCallback) {
      //用户首次进入不刷新
      if (localStorage.getItem("isfirstin")) {
        finshCallback()
      } else {
        this.getChatLogDetailList(finshCallback, "init")
      }
    },
    onPulldown(finshCallback) {
      if (this.chatPage.page < this.totalpage) {
        this.chatPage.page++
        this.getChatLogDetailList(finshCallback)
      } else {
        finshCallback()
      }
    },
    //上传前压缩
    createImage(event){
      let file = event.target.files;
      let that = this;
      _each(file, (v, i) => {
        //判断图片上传类型
        var tempIndex = v.type.lastIndexOf("/");
        var imgType = v.type.substring(tempIndex+1);
        if(imgType!=="jpg"&&imgType!=="jpeg"&&imgType!=="png"&&imgType!=="gif"){
          that.$toast("不支持的图片类型");
          // this.isupload = false;
          return;
        }
        //100k以上压缩
        if(v.size<102400){
            that.upload(v);
        }else{
          lrz(v, { quality: 0.8 }).then(function(rst) {
              v=rst.file;
              that.upload(v);
              return rst;
            }).catch(function (err) {
                // 处理失败会执行
                console.log(err)
            })
            .always(function () {
                // 不管是成功失败，都会执行
            });
        }
      })  
    },
    upload(v) {
        const self = this;
        const fd = new window.FormData();
        fd.append("token", this.token);
        fd.append("file", v);
        axios
          .post("https://upload-z2.qiniup.com", fd, {
            headers: {
              "Content-Type": "multipart/form-data"
            },
            timeout: 40000,
          })
          .catch(error => {
            this.$toast("图片上传超时!!");
          })
          .then(res => {
            var newimg = new Object();
            var thumbnailslistimg = new Object();
            newimg.src = "https://youlingqinius.wonderlandnet.cn/" + res.data.key;
            thumbnailslistimg.src =
              "https://youlingqinius.wonderlandnet.cn/" + res.data.key;
            let qiniuimgurl =
              "https://youlingqinius.wonderlandnet.cn/" + res.data.key + "?imageInfo";
            this.content = "https://youlingqinius.wonderlandnet.cn/" + res.data.key + "?imageMogr2/auto-orient";
            //发送图片
            const param = {
              type: 2,
              content: this.content
            };

            let _this = this;
            api.saveChatLogDetail(param).then(res => {
              if (res.success) {
                this.getTime();
                let tempmsgobj = new Object();
                tempmsgobj.headUrl = localStorage.getItem("headImg");
                tempmsgobj.chatType = 1;
                tempmsgobj.contentType = 2;
                tempmsgobj.content = _this.content;
                tempmsgobj.createTimeStamp = _this.tempdate;
                _this.chatLogDetailList.push(tempmsgobj);
                _this.$bus.$emit('scrollToBottom');
                _this.content = "";
              } else {
                this.$toast(res.msg);
              }
            });
          });
    
    },

    getqiuniutoken() {
      api.Queryuploadtoken({})
        .then(res => {
          if (res.success) {
            this.token = res.token;
          }
        })
        .catch(error => { });
    },
    sendMsg() {
      if (this.content == "") {
        this.$toast("请输入消息");
        return;
      }
    
      const param = {
        type: 1,
        content: this.content
      };

      api.saveChatLogDetail(param).then(res => {
        if (res.success) {
          let tempmsgobj = new Object();
          this.getTime();
          if (this.chatLogDetailList.length!=0&&this.chatLogDetailList[this.chatLogDetailList.length - 1].chatType == 1) {
            let lasttimestamp = new Date(this.chatLogDetailList[this.chatLogDetailList.length - 1].createTimeStamp.replace(/-/g, '/'))
            let datenow = new Date(this.tempdate.replace(/-/g, '/'))
            let difftime = this.gettimediff(lasttimestamp, datenow)
            if (difftime > 300000) {
              tempmsgobj.isshow = true
            } else {
              tempmsgobj.isshow = false
            }
          } else {
            tempmsgobj.isshow = true
          }
          
          //判断当前发送的消息时间戳是否需要显示
          this.content = this.$util.getTextUrl(this.content);//识别链接
          tempmsgobj.headUrl = localStorage.getItem("headImg");
          tempmsgobj.chatType = 1;
          tempmsgobj.contentType = 1;
          tempmsgobj.content = this.content;
          tempmsgobj.createTimeStamp = this.tempdate;
          this.chatLogDetailList.push(tempmsgobj);
          this.$bus.$emit('scrollToBottom');
          this.content = "";
   
        } else {
          this.$toast(res.msg);
        }
      });

    },
    //拼接数组
    unshiftArray(oldarr, newarr) {
      _each(newarr, (v) => {
        oldarr.unshift(v)
      })
    },
    getChatLogDetailList(callback, flag) {
      if (flag == "init") {
        this.chatPage.page = 1
        this.chatLogDetailList = []
      }
      let p = new Promise((resolve, reject) => {
        api.getChatLogDetailList(this.chatPage).then(res => {
          if (res.success) {
            this.unshiftArray(this.chatLogDetailList, res.data.list);
            this.totalpage = res.data.totalPage;
            //首次登陆自动回复
            let tempfirstin = localStorage.getItem("isfirstin")
            if (tempfirstin == null) {
              this.getTime();
              this.autoreply.createTimeStamp = this.tempdate;
              this.chatLogDetailList.push(this.autoreply);
              localStorage.setItem("isfirstin", JSON.stringify(true));
            }
            _each(this.chatLogDetailList, (v, j) => {
              if(v.contentType==1){
                v.content = this.$util.getTextUrl(v.content);
              }
              v.isshow = false;
            })
            this.settimestampshow();
            callback && callback();
          } else {
            this.$toast(res.msg || "出现错误")
            callback && callback();
          }
          resolve("获取留言内容");
        });
      });
      return p;
    },
    //时间戳显示规则
    settimestampshow() {
      _each(this.chatLogDetailList, (v, i) => {
        if (this.chatLogDetailList[i].chatType == 2) {
          if (this.adminstarttimestamp == "") {
            this.adminstarttimestamp = new Date(this.chatLogDetailList[i].createTimeStamp.replace(/-/g, '/'))
            this.userstarttimestamp = ""
            this.chatLogDetailList[i].isshow = true
          }

          if (i == 0) {
            this.chatLogDetailList[i].isshow = true
          } else if (i + 1 < this.chatLogDetailList.length) {
            let date = new Date(this.chatLogDetailList[i + 1].createTimeStamp.replace(/-/g, '/'));
            let timediff = this.gettimediff(this.adminstarttimestamp, date)
            if (timediff > 300000) {
              this.chatLogDetailList[i + 1].isshow = true
              this.adminstarttimestamp = new Date(this.chatLogDetailList[i + 1].createTimeStamp.replace(/-/g, '/'))
            }
          }
        } else if (this.chatLogDetailList[i].chatType == 1) {
          if (this.userstarttimestamp == "") {
            this.userstarttimestamp = new Date(this.chatLogDetailList[i].createTimeStamp.replace(/-/g, '/'))
            this.adminstarttimestamp = ""
            this.chatLogDetailList[i].isshow = true
          }
          if (i == 0) {
            this.chatLogDetailList[i].isshow = true
          } if (i + 1 < this.chatLogDetailList.length) {
            let dates = new Date(this.chatLogDetailList[i + 1].createTimeStamp.replace(/-/g, '/'));
            let timediffs = this.gettimediff(this.userstarttimestamp, dates)
            if (timediffs > 300000) {
              this.chatLogDetailList[i + 1].isshow = true
              this.userstarttimestamp = new Date(this.chatLogDetailList[i + 1].createTimeStamp.replace(/-/g, '/'))
            }
          }
        }
      })
    },
    //计算时间差
    gettimediff(starttime, endtime) {
      let timediff = endtime.getTime() - starttime.getTime()
      return timediff
    },
    getTime() {
      let date = new Date();
      this.year = date.getFullYear();
      this.month =
        date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1;
      this.date = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
      this.hour =
        date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
      this.minute =
        date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
      this.second =
        date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
      this.tempdate =
        this.year +
        "-" +
        this.month +
        "-" +
        this.date +
        " " +
        this.hour +
        ":" +
        this.minute +
        ":" +
        this.second;
    },
    saveimgtolocal(src){
      this.imgstr=[];
      this.imgstr.push(src);
      window.location.href= "image://?url=" + this.imgstr + "&currentIndex="+0;
    },
     updatanotreadnum(){//更新消息未读数
        const numobj = { notReadLike:this.notreadmsg.notReadLike, notReadComment: this.notreadmsg.notReadComment,
                              notreadleavemsg:0,notreadrec:this.notreadmsg.notreadrec,notReadSysMsg:this.notreadmsg.notReadSysMsg};
        this.changenotreadmsg(numobj); 
    }
  },
  components: {
    ylheader,
    PullToRefresh,
  }
};
</script>
<style>
.mint-field-clear {
  opacity: 0;
}

.mint-field .mint-cell-value {
  flex: 0.75;
  border-bottom: 1px solid #c2c2c2
}

.mint-field-core {
  line-height: 0;
  font-size: 0.28rem;
  color: #b3b3b3;
}
</style>

<style lang="less" scoped>
.chatlist {
  border-radius: 0 8px 8px 8px 8px;
  position: relative;
  /* padding: 10px; */
  height: 100%;
  /* Prevent native touch events on Windows */
  -ms-touch-action: none;
  /* Prevent the callout on tap-hold and text selection */
  -webkit-touch-callout: none;
  user-select: none;
  text-size-adjust: none;
}




/* .chatlist ul {
  min-height: 500px;
} */

.chatlist ul .chat-mine {
  text-align: right;
  padding-left: 20px;
  padding-right:50px;
}

.chatlist ul li {
  position: relative;
  /*font-size: 0;*/
  margin-bottom: 10px;
  padding-left: 50px;
  margin: 0.4rem 0.3rem 0.4rem 0.3rem;
}

.chat-mine .chat-user {
  left: auto;
  right: 3px;
}

.chat-user {
  position: absolute;
  left: 3px;
  // .pendant{
  //   width: 0.9rem;
  //   height: 0.9rem;
  //   position: absolute;
  //   // right: 0.1rem;
  //   left: -0.07rem;
  //   bottom: 0.02rem
  // }
    .pendant{
      width: 100%;
      height: 100%;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }
    .pendant-container{
      width: 50px;
      position: relative;
      height: 50px;
    }
}

.chat-text,
.chat-user {
  display: inline-block;
  vertical-align: top;
  /*font-size: 14px;*/
}

.chat-user img {
  width: 40px;
  height: 40px;
  border-radius: 100%;
}

.time {
  width: 100%;
}

cite {
  left: auto;
  right: 60px;
  text-align: right;
}

cite {
  font-style: normal;
  line-height: 24px;
  font-size: 0.26rem;
  white-space: nowrap;
  color: #999;
  text-align: left;
}

cite i {
  font-style: normal;
  padding-left: 5px;
  padding-right: 5px;
  font-size: 0.22rem;
  color: #999
}

.chat-mine .chat-text {
  margin-left: 0;
  text-align: left;
  color: #fff;
}

.chat-text {
  position: relative;
  line-height: 22px;
  /*margin-top: 25px;*/
  padding: 10px 12px;
  border-radius: 8px 0px 8px 8px;
  color: #333;
  word-break: break-all;
  max-width: 462px\9;
}

.chat-img-text {
  position: relative;
  line-height: 22px;
  /*margin-top: 25px;*/
  padding: 10px 0;
  border-radius: 8px 0px 8px 8px;
  color: #333;
  word-break: break-all;
  max-width: 462px\9;
}

.chat-littegreen-text {
  display: inline-block;
  background-color: #fff;
  color: #494949;
  position: relative;
  line-height: 22px;
  padding: 10px 12px;
  border-radius: 0 8px 8px 8px;
  margin-right: 0.8rem;
  word-break: break-all;
  max-width: 462px\9;
  font-size: 0.26rem
}

.chat-text,
.chat-user {
  display: inline-block;
  vertical-align: top;
  font-size: 13px;
}

.chat-text img {
  max-width: 100%;
  vertical-align: middle;
}

.chat-user {
  position: absolute;
  left: 3px;
  top: -5px;
}
.foot {
  width: 100%;
  position: absolute;
  bottom: 0px;
  left: 0px;
  background-color: #f8f8f8;
  height: 1rem;
  line-height:1rem
}

.foot .con {
  position: absolute;
  left: 0;
  right: 180px;
  width:100%;
  padding:0 2rem 0 0.3rem;
  height: 100%;
  outline-color: invert ;  
  outline-style: none ;  
  outline-width: 0px ;  
  border: none ;  
  border-style: none ;  
  text-shadow: none ;  
  -webkit-appearance: none ;  
  -webkit-user-select: text ;  
  outline-color: transparent ;  
  box-shadow: none; 
  font-size:0.28rem;
  color:#b3b3b3;
}

.foot .btn-plus {
  width: 28px;
  padding: 9px 3px;
  position: absolute;
  left: 0px;
  border-left: 1px solid #d9d9d9;
}

.foot .btn-plus i {
  font-size: 2em;
  color: #ccc;
}

.foot .btn-face {
  width: 28px;
  padding: 9px 3px 9px 0px;
  position: absolute;
  left: 35px;
  /*border-right: 1px solid #d9d9d9;*/
}

.foot .btn-face i {
  font-size: 2em;
  color: #d9d9d9;
}

.btn {
  display: inline-block;
  vertical-align: top;
  font-size: 14px;
  line-height: 32px;
  margin-left: 5px;
  padding: 0 6px;
  color: #fff;
}

.btn-send {
  padding: 0.05rem 0.14rem 0.42rem 0.14rem;
  height: 0.4rem;
  line-height:0.4rem;
  color: #949494;
  border: 1px solid #949494;
  border-radius: 3px;
  position: absolute;
  right: 0.3rem;
  top:23%
}

.myinput {
  height: 0.8rem;;
  width: 0.4rem;
  position: absolute;
  right: 1.35rem;
  opacity: 0;
}
.body-sep {
  height: 1px;
  background-color: #c2c2c2;
  position:absolute;
  right:2rem;
  left: 0.3rem;
  bottom:0.15rem;
}
.withdraw{
  padding-right: 50px;
  font-size: 0.28rem;
  color: #909090;
}
.chat-head{
    height: 0.8rem;
    width: 0.8rem;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}
.v-h{
  // top:0.6rem;
  // left: 0.62rem;
}
</style>